import React, {useEffect, useRef} from 'react';

import type {DataNode} from "antd/es/tree";
import {Button, Card, Input, Space, Tag} from "antd";
import Tree from "antd/es/tree/Tree";
import {useLocation} from "react-router-dom";

import {SecurityRole} from "type/SecurityRole";
import {requestGet, requestPut} from "util/request";
import {AuthorityHandleTreeData} from "type/AuthorityHandleTreeData";
import {EditOutlined, SettingOutlined} from "@ant-design/icons";
import {compareArray} from "util/compare";
import {requestMap} from "util/ColumnsUtil";
import GlobalHandler from "global/GlobalHandler";
import LogFactory from "log/LogFactory";

const log = LogFactory.getLog("RoleRequestComponent") ;

/**
 * 美化角色权限树
 * @param treeData
 */
const beautifyRoleTree = (treeData: DataNode[]): DataNode[]  => {
   return treeData.map((item,index) => {
       if (item.children){
              item.children = beautifyRoleTree(item.children) ;
       }
       let str = (item.title as string).split(":") ;
        item.title = (<Space>
            {requestMap.get(str[0])}
            <Tag>{str[1]}</Tag>
        </Space>) ;
        return item ;
    }) ;

    // return [] ;
} ;

const RoleRequestComponent = () => {
    const role: SecurityRole = useLocation().state ;

    const roleKeys = useRef<string[]>([]);
    // log.debug("role",role) ;
    const [checkedKeys,setCheckedKeys] = React.useState<string[]>([]) ;
    const [expandedKeys,setExpandedKeys] = React.useState<string[]>([]) ;
    const [treeData, setTreeData ] = React.useState<DataNode[]>([]) ;

    const onCheck = (checkedKeysValue: any) => {
        setCheckedKeys(checkedKeysValue) ;
    };
    const onExpand = (expandedKeysValue: any) => {
        setExpandedKeys(expandedKeysValue) ;
    };

    useEffect(() => {
        requestGet<AuthorityHandleTreeData>("/manager/security-role-path/authority-tree/" + role.id)
            .then(res => {
                // log.requestDebug("请求获取角色权限树",res) ;
                if(!res.success){
                    return ;
                }
                roleKeys.current = res.data.authorityKeys ;
                setTreeData(beautifyRoleTree(res.data.treeData)) ;
                setCheckedKeys(res.data.authorityKeys) ;
                setExpandedKeys(res.data.expandKeys);
            });
    }, []);
    /**
     * 刷新角色路径权限
     */
    const refreshRolePath = () => {
        requestGet<number>("/root/refresh-role-path")
            .then(res => {
                log.debug("刷新角色路径权限",res) ;
            }) ;
    } ;

    const onsubmit = () => {
        log.debug("修改角色路径权限",checkedKeys) ;
        let update = compareArray(roleKeys.current, checkedKeys) ;
        log.debug("修改结果比较",update) ;
        if (update.isUpdate){
            update.id = role.id ;
            delete update.isUpdate ;
            requestPut<number>("/manager/security-role-path",update)
                .then(res => {
                    // log.requestDebug("修改角色路径权限",res) ;
                    if (res.data > 0){
                        GlobalHandler.getInstance().sendSuccessMessage("修改成功!") ;
                        roleKeys.current = checkedKeys ;
                    }else {
                        GlobalHandler.getInstance().sendWarningMessage("修改失败!") ;
                    }
                }) ;
        }
    } ;

    return (
        <>
            <Card
                title={"角色权限修改"}
                extra={ <Space.Compact>
                    <Button type="primary">{role.authority}</Button>
                    <Input disabled defaultValue={role.explain} />
                </Space.Compact>}
                actions={[
                    <Button><SettingOutlined key="setting" /> : {treeData.length}</Button>,
                    <Button onClick={onsubmit} type={"primary"}><EditOutlined key="edit" />权限修改</Button>,
                    <Button onClick={refreshRolePath}>刷新角色权限</Button>,
                ]}
                >
                <Tree
                    checkable={true}
                    onCheck={onCheck}
                    onExpand={onExpand}
                    autoExpandParent={true}
                    expandedKeys={expandedKeys}
                    treeData={treeData}
                    checkedKeys={checkedKeys}
                />
            </Card>
        </>
    );
};

export default RoleRequestComponent;